package com.wang.utils.stack;

/**
 * @author 10570
 * @date 2021/7/24 22:12
 */

import java.util.Scanner;
import java.util.Stack;

/**
 * 1、数组模拟栈
 * 2、定义top表示栈顶，为-1
 * 3、入栈的操作，top++；stack[top] = data;
 * 4、出栈：int value = stack[top];top-- return value
 */
public class ArrayStackDemo {
    public static void main(String[] args) {
        ArrayStack arrayStack = new ArrayStack(5);
        String key = "";
        boolean loop = true;//是否退出
        Scanner scanner = new Scanner(System.in);
        while (loop){
            System.out.println("show:");
            System.out.println("exit:");
            System.out.println("push:");
            System.out.println("pop:");
            System.out.println("请输入key；");
            key = scanner.next();
            switch (key){
                case "show":
                    arrayStack.list();
                    break;
                case "exit":
                    scanner.close();
                    loop = false;
                    break;
                case "push":
                    System.out.println("请输入一个数：");
                    int value = scanner.nextInt();
                    arrayStack.push(value);
                    break;
                case "pop":
                    System.out.printf("出栈的数据%d\n",arrayStack.pop());
                    break;
                default:
                    break;
            }

        }
        System.out.println("程序退出");
    }
}
class ArrayStack{
    private int maxSize ; //最大
    private int[] stacks; //数组栈
    private int top = -1; //栈顶初始化为-1

    public ArrayStack(int maxSize) {
        this.maxSize = maxSize;
        stacks = new int[maxSize];
    }
    public ArrayStack(){

    }

    //栈是否满了
    public boolean isFull(){
        return top == maxSize-1;
    }

    public boolean isEmpty(){
        return top == -1;
    }
    //入栈
    public void push(int value){
        if (isFull()){
            return;
        }
        top ++;
        stacks[top] = value;
    }
    //出栈 --将栈顶返回
    public int pop(){
        if (isEmpty()){
            throw  new RuntimeException("栈空了");
        }
        int value = stacks[top];
        top--;
        return value;
    }

    //遍历栈--遍历要从栈顶显示数据
    public void list(){
        if (isEmpty()){
            System.out.println("没有数据");
            return;
        }
        for (int i = top ; i >= 0; i--){
            System.out.printf("stacks[%d]= %d\n",i,stacks[i]);
        }
    }


}
